package cn.kaicity.app.dimiconnect

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.util.*

class MainActivity : FlutterActivity() {

    private val CHANNEL = "cn.kaicity/flutter"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->

            when (call.method) {

                "getIp" -> result.success(getIp())

                "readUserInfo" -> result.success(readUserInfo())

                "saveUserInfo" -> saveUserInfo(call.arguments.toString())

                "openUrl" -> openBrowser(call.arguments.toString())

                else -> result.notImplemented()
            }

        }
    }

    private fun getIp(): String {
        var ip = ""
        try {
            val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
            while (en.hasMoreElements()) {
                val inter: NetworkInterface = en.nextElement()
                val enumIpAdd: Enumeration<InetAddress> = inter.inetAddresses
                while (enumIpAdd.hasMoreElements()) {
                    val interAddress: InetAddress = enumIpAdd.nextElement()
                    if (!interAddress.isLoopbackAddress && interAddress is Inet4Address) {
                        if (interAddress.hostAddress.toString().startsWith("17"))
                            ip = interAddress.hostAddress.toString()
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ip
    }

    private fun readUserInfo(): String {
        val sh = getSharedPreferences("user", Context.MODE_PRIVATE)
        return sh.getString("userInfo", "")!!
    }

    private fun saveUserInfo(info: String) {

        val edit = getSharedPreferences("user", Context.MODE_PRIVATE).edit()
        edit.putString("userInfo", info)
        edit.apply()
    }

    private fun openBrowser(url: String) {
        val intent = Intent()
        intent.action = Intent.ACTION_VIEW
        intent.data = Uri.parse(url)
        startActivity(intent)
    }
}
